from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature

from mall import settings
from users.models import User


def generic_active_url(user_id, email):
    # 创建序列化器
    serializer = Serializer(settings.SECRET_KEY, 3600)
    # 组织数据
    data = {
        'id': user_id,
        'email': email
    }
    # 对数据进行处理
    token = serializer.dumps(data)
    # 返回url
    return 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()


def get_active_user(token):
    # 创建序列化器
    serializer = Serializer(settings.SECRET_KEY, 3600)
    # 对token解析,判断异常
    try:
        result = serializer.loads(token)
    except BadSignature:
        return None
    else:
        id = result.get('id')
        email = result.get('email')
        try:
            user = User.objects.get(id=id, email=email)
        except BadSignature:
            return None
        else:
            return user
